package com.ericsson.mq.consumer;

import cn.hutool.core.date.DateUtil;
import com.ericsson.mq.constants.RabbitMqConsts;
import com.ericsson.mq.domain.EnipClearAlarmObject;
import com.ericsson.mq.service.EnmAlarmService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j(topic = "mqAlarmConsumer")
@Lazy(false)
@Component
@RabbitListener(queues = RabbitMqConsts.QUEUE_DELAY, autoStartup = "false")
public class QueueDelayConsumer {

    @Autowired
    EnmAlarmService enmAlarmService;

    @RabbitHandler
    public void directHandlerManualAck(EnipClearAlarmObject enipClearAlarmObject, Message message, Channel channel) {
        //  如果手动ACK,消息会被监听消费,但是消息在队列中依旧存在,如果 未配置 acknowledge-mode 默认是会在消费完毕后自动ACK掉
        final long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.debug("delay queue,manual ACK,receive message success now time is {},message is{}", DateUtil.now(),enipClearAlarmObject);
            enmAlarmService.doClearService(enipClearAlarmObject);
            // 通知 MQ 消息已被成功消费,可以ACK了
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            log.error("delay queue,consumer failed");
            /*try {
                // 处理失败,重新压入MQ
                channel.basicRecover();
            } catch (IOException e1) {
                e1.printStackTrace();
            }*/
        }
    }
}
